<template>
  <div style="width: 100vw; height: 100vh">
    <NuxtLayout name="background">
      <div class="context_box">
        <a-form ref="formRef" :model="formState" :rules="rules">
          <a-form-item label="" name="cetName">
            <a-input
              v-model:value="formState.cetName"
              placeholder="请输入真实姓名"
            >
              <template #prefix> <LockOutlined /> </template>
            </a-input>
          </a-form-item>
          <a-form-item label="" name="eMail">
            <a-input-group compact style="display: flex">
              <a-input v-model:value="formState.eMail" placeholder="请输入邮箱">
                <template #prefix>
                  <LockOutlined />
                </template>
              </a-input>
              <a-button
                type="primary"
                @click="getCode"
                :disabled="getCodeTime > 0"
                >{{ getCodeTitle }}</a-button
              >
            </a-input-group>
          </a-form-item>
          <a-form-item label="" name="passWord">
            <a-input-password
              v-model:value="formState.passWord"
              placeholder="请输入密码"
              autocomplete="off"
            >
              <template #prefix> <LockOutlined /> </template>
            </a-input-password>
          </a-form-item>
          <a-form-item label="" name="code">
            <a-input
              v-model:value="formState.code"
              placeholder="请输入验证码"
              style="width: 100%"
            >
              <template #prefix> <LockOutlined /> </template>
            </a-input>
          </a-form-item>
          <a-form-item>
            <div class="login_button">
              <a-button type="primary" :loading="loading" @click="onSubmit"
                >注册</a-button
              >
              <a-button type="primary" @click="goLogin">去登陆</a-button>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </NuxtLayout>
  </div>
</template>

<script lang="ts" setup>
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { reactive, ref, UnwrapRef } from "vue";
import { RegisterInterface, SendEMailInterface } from "~~/types/index";
import { LockOutlined } from "@ant-design/icons-vue/lib/icons";
import { useMyFetch } from "~~/utils/useMyFetch";
import { message } from "ant-design-vue";

useHead({
  title: "注册",
});

const router = useRouter();

const formRef = ref();

let loading = ref<boolean>(false);

let getCodeTime = ref<number>(0);

let formState: UnwrapRef<RegisterInterface> = reactive({});

let rules = {
  eMail: [{ required: true, validator: emailvalidate, trigger: "blur" }],
  cetName: [
    {
      required: true,
      message: "真实姓名不能为空",
      trigger: "blur",
    },
  ],
  passWord: [
    {
      required: true,
      message: "密码不能为空",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "验证码不能为空",
      trigger: "blur",
    },
  ],
};

let getCodeTitle = computed(() => {
  if (getCodeTime.value == 0) return "获取验证码";
  return `${getCodeTime.value}重新获取`;
});

//获取验证码
const getCode = async () => {
  let regNeg =
    /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
  if (!formState.eMail || !regNeg.test(formState.eMail)) {
    return message.error("邮箱格式错误");
  }
  getCodeTime.value = 60;
  let timer: NodeJS.Timeout = setInterval(() => {
    getCodeTime.value--;
    if (getCodeTime.value == 0) clearTimeout(timer);
  }, 1000);
  const sendData: SendEMailInterface = {
    eMail: formState.eMail!,
  };
  const { data } = await useMyFetch<boolean | null>("/reg/sendEmailCode", {
    method: "POST",
    body: sendData,
  });
  if (data) message.success("发送成功");
};

//注册
const onSubmit = () => {
  let body = JSON.parse(JSON.stringify(formState));
  formRef.value
    .validate()
    .then(async () => {
      loading.value = true;
      let timer: NodeJS.Timeout = setTimeout(() => {
        loading.value = false;
        clearTimeout(timer);
      }, 2000);
      const { data } = await useMyFetch("/reg/register", {
        body: body,
        method: "POST",
      });
      if (data) message.success("注册成功");
    })
    .catch((error: ValidateErrorEntity<RegisterInterface>) => {
      console.log("error", error);
    });
};

//登录
const goLogin = () => {
  router.replace("/login");
};
</script>
